package Servlet;

import Bean.Ticket;
import Service.TicketService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-03-10
 * Time: 11:15
 */
//购买机票
@WebServlet("/OrderFlightServlet")
public class OrderFlightServlet extends HttpServlet {
    private TicketService ticketService = new TicketService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf8");

        //获取航班id
        String flightId = req.getParameter("flightId");
        String ticketType = req.getParameter("classType");
        System.out.println("[ticketType] "  +ticketType);
        String seatNumber = req.getParameter("seatNumber");
        double price = Double.parseDouble(req.getParameter("finalPrice"));
        //获取登录用户的userId(登录的用户就是购票的用户)
        HttpSession session = req.getSession();
        String userId = (String) session.getAttribute("LoginUserId");
        boolean ok = ticketService.reservation(flightId,ticketType,seatNumber,price,userId);
        if (ok) {
            req.setAttribute("status", "success");
            req.setAttribute("message", "机票预订成功!");
            req.setAttribute("redirectUrl", "user_index.jsp");
            req.setAttribute("waitSeconds", 1);
        } else {
            req.setAttribute("status", "error");
            req.setAttribute("message", "机票预订失败,该座位号已被选择!!");
            req.setAttribute("redirectUrl", "user_index.jsp");
            req.setAttribute("waitSeconds", 2);
        }
        req.getRequestDispatcher("skip.jsp").forward(req,resp);
    }
}
